package com.zzzzzz.account;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zzzzzz.account.model.User;
import com.zzzzzz.account.service.UserService;

/**
 * A Spring MVC interceptor that adds the currentUser into the request as a request attribute
 * before the JSP is rendered.  This operation is assumed to be fast because the User should be
 * cached in the Hibernate second-level cache.
 */
public class CurrentUserInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private UserService userService;

	@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Add the current user into the request
        User currentUser = userService.findCurrentUser();
    	
        if( currentUser != null ) {
        	request.setAttribute("currentUser", currentUser);
        }
    }

}
